package com.zzj.ecology.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzj.ecology.commons.prop.Global;
import com.zzj.ecology.commons.utils.http.apache.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址工具类
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://apis.juhe.cn/ip/ipNew";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";

        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (Global.isAddressEnabled()) {
            Map<String, String> params = new HashMap<>();
            params.put("ip", ip);
            params.put("key", "533ca0ccaa28b025a40e08435b71f4ea");
            String rspStr = HttpUtils.sendPost(IP_URL, params);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            JSONObject obj;
            try {
                obj = JSON.parseObject(rspStr);
                JSONObject data = obj.getJSONObject("result");
                String country = data.getString("Country");
                String province = data.getString("Province");
                String city = data.getString("City");
                address = country + " " + province + " " + city;
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }
}
